package net.yla.smartbus.core.util;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * APP支付工具类
 * @author TangWenBo
 * @date 2019-05-08 09:26
 **/
public class AppPayUtil {

//    /**
//     * 下单接口
//     * @param amt:订单金额
//     * @param request:请求
//     * @return JSONObject
//     */
//    public static PayUnitedResponse buildPrePayment(String amt, HttpServletRequest request) {
//        //微信下单接口所需的参数
//        Map<String, String> paramsMap = new HashMap<String, String>();
//        paramsMap.put("appid", PayConstant.appId);
//        paramsMap.put("mch_id", PayConstant.mchId);
//        paramsMap.put("nonce_str", AppPayUtil.creatReqSeq());
//        paramsMap.put("body", "FieldOfVisionQuery");
//        paramsMap.put("out_trade_no", RandomUtil.randomStringFixLength(12));
//        paramsMap.put("total_fee", amt);
//        //获取当前用户的ip
//        String ip = AppPayUtil.getIpAddr(request);
//        paramsMap.put("spbill_create_ip", ip);
//        //配置回调地址
//        String noticeUrl = PayConstant.servicePath + "/appPay/payNotice";
//        paramsMap.put("notify_url", noticeUrl);
//        paramsMap.put("trade_type", "APP");
//        //普通商品订单
//        paramsMap.put("attach", "ORDER");
//        paramsMap.put("time_start", System.currentTimeMillis() + "");
//        //设置订单失效时间
//        int offset = 1;
//        String timeExpire = DateFormatUtils.format(JodaDateUtil.getOffsetDate(offset), "yyyyMMddHHmmss");
//        paramsMap.put("time_expire", timeExpire);
//        // 计算sign
//        String sign = MicroPayCore.buildMysign(paramsMap, PayConstant.appKey).toUpperCase();
//        paramsMap.put("sign", sign);
//        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//        String bodyContent = buildWeiXinRequest(paramsMap);
//        String reback = HttpClientUtil.doPost(url, bodyContent);
//        PayUnitedResponse payUnitedResponse = null;
//        try {
//            if (reback != null) {
//                payUnitedResponse = AppPayUtil.xmlToPayUnitedResponse(reback);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return payUnitedResponse;
//    }
//
//    /**
//     * 构建微信支付的页面请求
//     * @return AppPayRequest
//     */
//    public static AppPayRequest buildMsg(PayUnitedResponse payUnitedResponse) {
//        String timeStamp = System.currentTimeMillis()/1000 + "";
//        String nonceStr = creatReqSeq();
//        String packageMsg = "Sign=WXPay";
//        String paySgin = paySign(packageMsg, PayConstant.appId, timeStamp, nonceStr, payUnitedResponse.getMch_id(), payUnitedResponse.getPrepay_id());
//
//        AppPayRequest appPayRequest = new AppPayRequest();
//        appPayRequest.setTimestamp(timeStamp);
//        appPayRequest.setNonceStr(nonceStr);
//        appPayRequest.setPackageMsg(packageMsg);
//        appPayRequest.setPartnerId(payUnitedResponse.getMch_id());
//        appPayRequest.setPrepayId(payUnitedResponse.getPrepay_id());
//        appPayRequest.setSign(paySgin);
//        appPayRequest.setAppId(PayConstant.appId);
//
//        return appPayRequest;
//    }

    /**
     * 生成支付流水号
     * @return String
     */
    public static String creatReqSeq() {
        String appId = "11";
        String seq = appId + StringEx.getRandomStringByDate(18) + Integer.valueOf((int) ((Math.random() * 9 + 1) * 10000));
        return seq;
    }

    /**
     * 获取调用JSAPI支付的服务器ip
     * @param request
     * @return String
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(ip.contains(",")) {
            String[] ipArray = ip.split(",");
            if(ipArray.length > 0) {
                return ipArray[0];
            }
        }
        return ip;
    }

    /**
     * 构建预支付请求
     * @param param
     * @return
     */
    public static String buildWeiXinRequest(Map<String, String> param) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        sb.append("<appid>" + param.get("appid") + "</appid>");
        sb.append("<attach><![CDATA[" + param.get("attach") + "]]></attach>");
        sb.append("<body><![CDATA[" + param.get("body") + "]]></body>");
        sb.append("<mch_id>" + param.get("mch_id") + "</mch_id>");
        sb.append("<nonce_str>" + param.get("nonce_str") + "</nonce_str>");
        sb.append("<notify_url>" + param.get("notify_url") + "</notify_url>");
        sb.append("<out_trade_no>" + param.get("out_trade_no") + "</out_trade_no>");
        sb.append("<spbill_create_ip>" + param.get("spbill_create_ip") + "</spbill_create_ip>");
        sb.append("<total_fee>" + param.get("total_fee") + "</total_fee>");
        sb.append("<trade_type>" + param.get("trade_type") + "</trade_type>");
        sb.append("<sign><![CDATA[" + param.get("sign") + "]]></sign>");
        sb.append("<time_start>" + param.get("time_start") + "</time_start>");
        sb.append("<time_expire>" + param.get("time_expire") + "</time_expire>");

        sb.append("</xml>");
        return sb.toString();
    }

//    /**
//     * 解析调用统一支付接口响应报文
//     * @param msg
//     * @return PayUnitedResponse
//     * @date 2019/5/8 14:20
//     */
//    public static PayUnitedResponse xmlToPayUnitedResponse(String msg) {
//        PayUnitedResponse payUnitedResponse = new PayUnitedResponse();
//        Document doc = null;
//        try {
//            doc = DocumentHelper.parseText(msg);
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        }
//        Element root = doc.getRootElement();
//        String return_code = root.element("return_code").getTextTrim();
//
//        if ("SUCCESS".equals(return_code)) {
//            String result_code = root.element("result_code").getTextTrim();
//            if ("SUCCESS".equals(result_code)) {
//                String appid = root.element("appid").getTextTrim();
//                String mch_id = root.element("mch_id").getTextTrim();
//                String nonce_str = root.element("nonce_str").getTextTrim();
//                String sign = root.element("sign").getTextTrim();
//                String trade_type = root.element("trade_type").getTextTrim();
//                String prepay_id = root.element("prepay_id").getTextTrim();
//
//                payUnitedResponse.setAppid(appid);
//                payUnitedResponse.setMch_id(mch_id);
//                payUnitedResponse.setNonce_str(nonce_str);
//                payUnitedResponse.setReturn_code(return_code);
//                payUnitedResponse.setReslut_code(result_code);
//                payUnitedResponse.setSign(sign);
//                payUnitedResponse.setTrade_type(trade_type);
//                payUnitedResponse.setPrepay_id(prepay_id);
//            } else {
//                String err_code = root.element("err_code").getTextTrim();
//                String err_code_desc = root.element("err_code_des").getTextTrim();
//                payUnitedResponse.setReturn_msg(err_code_desc);
//            }
//        } else {
//            // 协议错误
//            String return_msg = root.element("return_msg").getTextTrim();
//            payUnitedResponse.setReturn_msg(return_msg);
//        }
//
//        return payUnitedResponse;
//    }
//
//
//
//    /**
//     * 二次签名
//     * @param packageMsg, appId, timeStamp, nonceStr, partnerId, prepayId
//     * @return java.lang.String
//     * @date 2019/5/8 14:21
//     */
//    private static String paySign(String packageMsg, String appId, String timeStamp, String nonceStr, String partnerId, String prepayId) {
//        Map<String, String> param = new HashMap<String, String>();
//        param.put("appid", appId);
//        param.put("timestamp", timeStamp);
//        param.put("noncestr", nonceStr);
//        param.put("package", packageMsg);
//        param.put("partnerid", partnerId);
//        param.put("prepayid", prepayId);
//        // 去除空串
//        Map<String, String> array = MicroPayCore.paraFilter(param);
//        String sign = MicroPayCore.buildMysign(array, PayConstant.appKey);
//        return sign;
//    }

    /**
     * 读取request数据
     * @param request
     * @return String
     */
    public static String readRequestMsg(HttpServletRequest request){
        java.io.BufferedReader bis = null;
        String line = null;
        String result = "";
        try {
            bis = new java.io.BufferedReader(new java.io.InputStreamReader(
                    request.getInputStream(),"UTF-8"));
            while ((line = bis.readLine()) != null) {
                result += line + "\r\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

//    public static PayNotify xmlToPayNotify(String msg){
//        PayNotify payNotify=new PayNotify();
//        try {
//            Document doc = DocumentHelper.parseText(msg);
//            Element root = doc.getRootElement();
//            String return_code = root.element("return_code").getTextTrim();
//            if("SUCCESS".equals(return_code)){
//                String result_code = root.element("result_code").getTextTrim();
//                if("SUCCESS".equals(result_code)){
//                    String appid = root.element("appid").getTextTrim();
//                    String mch_id = root.element("mch_id").getTextTrim();
//                    String nonce_str = root.element("nonce_str").getTextTrim();
//                    String sign = root.element("sign").getTextTrim();
//                    String openid = root.element("openid").getTextTrim();
//                    String is_subscribe = root.element("is_subscribe").getTextTrim();
//                    String trade_type = root.element("trade_type").getTextTrim();
//                    String bank_type = root.element("bank_type").getTextTrim();
//                    String total_fee = root.element("total_fee").getTextTrim();
//                    String cash_fee = root.element("cash_fee").getTextTrim();
//                    String fee_type = root.element("fee_type").getTextTrim();
//                    String transaction_id = root.element("transaction_id").getTextTrim();
//                    String out_trade_no = root.element("out_trade_no").getTextTrim();
//                    String attach = root.element("attach").getTextTrim();
//                    String time_end = root.element("time_end").getTextTrim();
//                    payNotify.setAppid(appid);
//                    payNotify.setAttach(attach);
//                    payNotify.setBank_type(bank_type);
//                    payNotify.setCash_fee(cash_fee);
//                    payNotify.setFee_type(fee_type);
//                    payNotify.setIs_subscribe(is_subscribe);
//                    payNotify.setMch_id(mch_id);
//                    payNotify.setNonce_str(nonce_str);
//                    payNotify.setOpenid(openid);
//                    payNotify.setOut_trade_no(out_trade_no);
//                    payNotify.setResult_code(result_code);
//                    payNotify.setReturn_code(return_code);
//                    payNotify.setSign(sign);
//                    payNotify.setTime_end(time_end);
//                    payNotify.setTotal_fee(total_fee);
//                    payNotify.setTrade_type(trade_type);
//                    payNotify.setTransaction_id(transaction_id);
//                }else{
//                    payNotify.setReturn_code("FAIL");
//                    payNotify.setReturn_msg("支付回调接口返回数据错误");
//                }
//            }else{
//                //协议错误
//                String return_msg = root.element("return_msg").getTextTrim();
//                payNotify.setReturn_code("FAIL");
//                payNotify.setReturn_msg(return_msg);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            payNotify.setReturn_code("FAIL");
//            payNotify.setReturn_msg("支付回调接口返回数据错误");
//        }
//
//        return payNotify;
//    }
//
//    /**
//     * 反馈支付平台
//     * @param backPayResult
//     * @throws IOException
//     */
//    public static void writeBack(PaymentResult backPayResult, HttpServletResponse response) throws IOException {
//        response.setContentType("text/html; charset=GBK");
//        // // 给支付平台反馈相应消息
//        PrintWriter printWriter = response.getWriter();
//        printWriter.write(backPayResult.getResponseMsg());
//        printWriter.flush();
//        printWriter.close();
//    }

}
